<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests; 
use App\Http\Controllers\Controller;
use DB;

class CateController extends Controller
{
	//封装方法
	static public function getCate(){
	// select *,concat(path,','id) as paths from cate order by paths;
    	$data = DB::table('cate') -> select(DB::raw("*,concat(path,',',id) as paths"))->orderBy('paths') -> get();
    	foreach ($data as $k => $v){
    		$l = substr_count($v['path'],',');
    		$data[$k]['name'] = str_repeat('|----', $l).$v['name'];
    	}
    	return $data;	
	}


    public function getAdd($id = ''){
   		
        return view('admin.cate.add',['data'=>self::getCate(),'id'=>$id]);
    }

    public function postInsert(Request $request){
    	$this->validate($request,[
    		'name'=>'required',
    		],[
    		'name.required'=>'分类名不能为空',
    		]);
   	$data = $request -> only('name','pid');
   		//处理路径
   	$pid = $request->input('pid');
   	if($pid==0){
   		$data['path'] = 0;
   	}else{
   		//通过pid查询父级
   		$s = DB::table('cate') -> where('id',$pid) ->first();
   		$data['path']=$s['path'].','.$s['id'];
   	}
   	
    //插入数据库
     $res = DB::table('cate')->insert($data);
    //处理结果
    if($res)
        {
            return redirect('/admin/cate/index') -> with('success','添加成功');
        }else{
            return back() -> with('error','添加失败');
        }
    }
	
    public function getIndex()
    {
    	
    	return view('admin.cate.index',['data'=>self::getCate()]);
    }
   
    public function getUpdate()
    {
   		$id = $_GET['id'];
   		$a = $_GET['a'];

   		$s = DB::table('cate') -> where('pid',$id)->first();
   		if($s && $a ==2){
   			return back() -> with('error','当前类别有子类不可关闭');
   		}
   		$res = DB::table('cate')->where('id',$id) ->update(['status'=>$a]);
   		if($res>0)
        {
            return redirect('/admin/cate/index') -> with('success','修改成功');
        }else{
            return back() -> with('error','修改失败');
    }
    
    }
}
